<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('imrStudentInfoVerify.fields.studentCode')" prop="studentCode">
        <el-input
          v-model="queryParams.studentCode"
          :placeholder="
            t('common.inputTextPlaceholder') + t('imrStudentInfoVerify.fields.studentCode')
          "
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('imrStudentInfoVerify.fields.studentName')" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          :placeholder="
            t('common.inputTextPlaceholder') + t('imrStudentInfoVerify.fields.studentName')
          "
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
          :disabled="advancedSearching"
        />
      </el-form-item>
      <el-form-item :label="t('imrStudentInfoVerify.fields.verifyStatus')" prop="verifyStatus">
        <el-select
          v-model="queryParams.verifyStatus"
          :placeholder="
            t('common.selectTextPlaceholder') + t('imrStudentInfoVerify.fields.verifyStatus')
          "
          clearable
          class="!w-240px"
          :disabled="advancedSearching"
        >
          <el-option :label="t('imrStudentInfoVerify.index.waiting')" value="待审核" />
          <el-option :label="t('imrStudentInfoVerify.index.passed')" value="已通过" />
          <el-option :label="t('imrStudentInfoVerify.index.rejected')" value="已拒绝" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" :disabled="advancedSearching">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery" :disabled="advancedSearching">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          plain-->
        <!--          @click="openForm('create')"-->
        <!--          v-hasPermi="['core:imr-student-info-verify:create']"-->
        <!--        >-->
        <!--          <Icon icon="ep:plus" class="mr-5px" />-->
        <!--          {{ t('action.add') }}-->
        <!--        </el-button>-->
        <!--        <el-button-->
        <!--          type="warning"-->
        <!--          plain-->
        <!--          @click="handleImport"-->
        <!--          v-hasPermi="['core:imr-student-info-verify:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:upload" class="mr-5px" />-->
        <!--          {{ t('action.import') }}-->
        <!--        </el-button>-->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['core:imr-student-info-verify:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
        <ConditionTree
          id="imrstudentinfoverify-condition-tree"
          :schemata="imrStudentInfoVerifySchema"
          @search="handleAdvanceSearch"
        />
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iImrStudentInfoVerify-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.studentCode')"
        field="studentCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.studentName')"
        field="studentName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.studentGrade')"
        field="studentGrade"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.studentClass')"
        field="studentClass"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.verifyType')"
        field="verifyType"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.verifyStatus')"
        field="verifyStatus"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.modifyFields')"
        field="modifyFields"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.remark')"
        field="remark"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.reviewerName')"
        field="reviewerName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.reviewTime')"
        field="reviewTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.reviewComments')"
        field="reviewComments"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('imrStudentInfoVerify.fields.createTime')"
        field="createTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :formatter="vxeDateFormatter"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="80"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row.id)">
            <template v-if="scope.row.verifyStatus === '待审核'">
              {{ t('action.audit') }}
            </template>
            <template v-else>
              {{ t('action.detail') }}
            </template>
          </el-button>
          <!--          <el-button-->
          <!--            link-->
          <!--            type="primary"-->
          <!--            @click="openForm('update', scope.row.id)"-->
          <!--            v-hasPermi="['core:imr-student-info-verify:update']"-->
          <!--          >-->
          <!--            {{ t('action.edit') }}-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            link-->
          <!--            type="danger"-->
          <!--            @click="handleDelete(scope.row.id)"-->
          <!--            v-hasPermi="['core:imr-student-info-verify:delete']"-->
          <!--          >-->
          <!--            {{ t('action.delete') }}-->
          <!--          </el-button>-->
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ImrStudentInfoVerifyForm ref="formRef" @success="getList" />
  <ExcelImportForm
    ref="importFormRef"
    object-name="联培学生信息变更审批"
    upload-url="/core/imr-student-info-verify/import"
    template-url="/core/imr-student-info-verify/get-import-template"
    @success="getList"
  />
  <Dialog
    :title="t('imrStudentInfoVerify.index.diffView.review')"
    v-model="dialogVisible"
    width="1200"
  >
    <div class="mb-[15px]" v-hasPermi="['core:imr-student-info-verify:update']">
      <el-button
        type="success"
        plain
        :disabled="formData && formData.verifyStatus !== '待审核'"
        @click="handleApprove"
        :loading="auditLoading"
      >
        <Icon icon="ep:check" class="mr-5px" />
        {{ t('imrStudentInfoVerify.index.diffView.approve') }}
      </el-button>
      <el-button
        type="danger"
        plain
        :disabled="formData && formData.verifyStatus !== '待审核'"
        @click="handleReject"
        :loading="auditLoading"
      >
        <Icon icon="ep:close" class="mr-5px" />
        {{ t('imrStudentInfoVerify.index.diffView.reject') }}
      </el-button>
    </div>
    <ImrStudentInfoDiffView
      v-if="studentInfo && studentInfoBackup"
      :student-info="studentInfo"
      :student-info-backup="studentInfoBackup"
    />
    <div v-hasPermi="['core:imr-student-info-verify:update']">
      <div class="review-title">{{ t('imrStudentInfoVerify.index.diffView.reviewComments') }}</div>
      <el-input
        v-if="formData"
        class="mt-[20px]"
        v-model="formData.reviewComments"
        maxlength="300"
        :placeholder="t('imrStudentInfoVerify.index.diffView.placeholder')"
        show-word-limit
        type="textarea"
        :disabled="formData && formData.verifyStatus !== '待审核'"
      />
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { vxeDateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ImrStudentInfoVerifyApi, ImrStudentInfoVerifyVO } from '@/api/core/imrstudentinfoverify'
import ImrStudentInfoVerifyForm from './ImrStudentInfoVerifyForm.vue'
import ExcelImportForm from '@/components/ExcelImportForm/index.vue'
import type { VxeTablePropTypes, VxeToolbarInstance, VxeTableInstance } from 'vxe-table'
import { imrStudentInfoVerifySchema } from '@/views/core/imrstudentinfoverify/schema'
import { useAppStore } from '@/store/modules/app'
import ImrStudentInfoDiffView from '@/views/core/imrstudent/components/ImrStudentInfoDiffView.vue'
import { ImrStudentVO } from '@/api/core/imrstudent'

/** 联培学生信息变更审批 列表 */
defineOptions({ name: 'ImrStudentInfoVerify' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const auditLoading = ref(false) // 审批操作中
const list = ref<ImrStudentInfoVerifyVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const advancedSearching = ref(false) // 高级搜索
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  accountId: undefined,
  studentCode: undefined,
  studentName: undefined,
  studentGrade: undefined,
  studentClass: undefined,
  verifyType: undefined,
  verifyStatus: undefined,
  modifyFields: undefined,
  oldValue: undefined,
  newValue: undefined,
  remark: undefined,
  reviewer: undefined,
  reviewerName: undefined,
  reviewTime: [],
  reviewComments: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const studentInfo = ref<ImrStudentVO>()
const studentInfoBackup = ref<ImrStudentVO>()

const dialogVisible = ref(false)

const reviewComments = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ImrStudentInfoVerifyApi.getImrStudentInfoVerifyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  advancedSearching.value = false
  ;(queryParams as any).advanced = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof ImrStudentInfoVerifyForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 导入 */
const importFormRef = ref<InstanceType<typeof ExcelImportForm>>()
const handleImport = () => {
  importFormRef.value?.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ImrStudentInfoVerifyApi.deleteImrStudentInfoVerify(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ImrStudentInfoVerifyApi.exportImrStudentInfoVerify(queryParams)
    download.excel(data, '联培学生信息变更审批.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleAdvanceSearch = (base64Advanced?: string) => {
  ;(queryParams as any).advanced = base64Advanced
  advancedSearching.value = !!base64Advanced
  handleQuery()
}

const formData = ref<ImrStudentInfoVerifyVO>()

const handleView = async (id: number) => {
  try {
    loading.value = true
    studentInfo.value = undefined
    studentInfoBackup.value = undefined
    formData.value = await ImrStudentInfoVerifyApi.getImrStudentInfoVerify(id)
    studentInfo.value = JSON.parse(formData.value?.newValue ?? '{}')
    studentInfoBackup.value = JSON.parse(formData.value?.oldValue ?? '{}')
    dialogVisible.value = true
  } finally {
    loading.value = false
  }
}

const handleApprove = async () => {
  try {
    auditLoading.value = true
    await ImrStudentInfoVerifyApi.adminVerifyImrStudentInfo({
      id: formData.value?.id,
      verifyStatus: '已通过',
      reviewComments: formData.value?.reviewComments
    })
    dialogVisible.value = false
    message.success(t('common.operSuccess'))
    await getList()
  } finally {
    auditLoading.value = false
  }
}

const handleReject = async () => {
  try {
    auditLoading.value = true
    await ImrStudentInfoVerifyApi.adminVerifyImrStudentInfo({
      id: formData.value?.id,
      verifyStatus: '已拒绝',
      reviewComments: formData.value?.reviewComments
    })
    dialogVisible.value = false
    message.success(t('common.operSuccess'))
    await getList()
  } finally {
    auditLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
.review-title {
  color: var(--el-text-color-primary);
  font-size: 13px;
  font-weight: 500;
  margin-top: 16px;
}
</style>
